<template>

    <div class="InventoryManage-page-content">
        <div class="InventoryManage-page-form">
            <el-input v-model="formData.drugName" style="width:240px" @change="handlePageChange(1)" @blur="handlePageChange(1)" placeholder="搜药品"
                :suffix-icon="Search" />
            <RadioGroupBtn @change="RadioGroupBtnChange" v-if="btnList.length > 1" style="margin-left: 14px;"
                :list="btnList"></RadioGroupBtn>
            <div class="InventoryManage-page-form-right">   
                
                <el-button type="primary" @click="add" v-btnPermission="'btn-inventory-add'"><el-icon style="margin-right: 5px;"><Plus /></el-icon>新建</el-button>
                <!-- <el-button type="primary" plain>导出</el-button> -->
               
            </div>
        </div>
        <div class="InventoryManage-page-table">
            <Table :columns="tableColumns" @selectionChange="selectionChange" :loading="loading"
                :data-source="tableData" />

        </div>
        <div class="InventoryManage-page-pagination">
            <Pagination style="margin-left: auto;" :key="pageSize + 'Pagination' + currentPage" :count="total"
                :page-size="pageSize" :pageNo="currentPage" @onPagechange="handlePageChange"
                @onSizechange="handleSizeChange" />
        </div> 
        <updata ref="updataRef" @closeDrawer="getDrugProfileListApi" />
    </div>

</template>

<script setup lang="ts">
import { ArrowDown, Search,Plus } from '@element-plus/icons-vue'
import type { TableProps, TableColumn } from '@/types/table';
import type { DrugInfo, DrugResponse, DrugTable, DrugForm } from '@/types/drug'
import { getDrugProfileList, addProfile, updateProfile, deleteProfile, enableProfile, disableProfile } from '@/api/drug'
import stores from '@/store';
import type { List as storageList } from '@/types/storage/index';
import updata from './common/updata.vue'

///药品分类;成药，中药，耗材
const DrugCategoryEnum = ref<any>(stores.useBaseDataStore().getEnumSelect('drugCategoryEnum'))
const UnitTypeEnum = ref<any>(stores.useBaseDataStore().getDictsSelect('UNIT'))
const updataRef = ref<InstanceType<typeof updata>>();

const add = () => {
    updataRef.value?.open(0, formData.value.storageId)
}

const storageInfo = defineProps<{ storageInfo: storageList }>();
const btnList = ref<any>([])
let list = [{ name: '全部', id: '' },]

for (let index = 0; index < DrugCategoryEnum.value.length; index++) {
    let item = DrugCategoryEnum.value[index];
    list.push({
        name: item.text,
        id: item.value
    })
}
btnList.value = list
const loading = ref<boolean>(false)

const formData = ref<DrugForm>({
    storageId: storageInfo.storageInfo.storageId,
    drugName: '',
    drugCategory: '',
    pageNo: 1,
    pageSize: 10,
})

const tableColumns: TableColumn[] = [
    { type: "selection", width: 50, prop: 'selection', label: '选择', fixed: 'left' },
    {
        prop: 'drugName',
        label: '药名',
        type: 'text',
        width: 200,
        permissions:'btn-inventory-xq',
        textColor:'color:#18B3AB',
        componentProps: {
            fixed: 'left',
        },
        buttonGroup: [
            {
                label: 'drugName',  type: 'text', click: (row: any) => {
                    updataRef.value?.open1(row.drugId, formData.value.storageId)
                }
            },
        ]
    },
    { prop: 'guige', label: '规格' },
    { prop: 'drugCategory', label: '药品分类' },
    { prop: 'mfrName', label: '生产厂家' },
    { prop: 'price', label: '售价' },
    { prop: 'stockQtyText', label: '库存数量' },

    
    { prop: 'isSplit', label: '是否允许拆零' },
    { prop: 'nearestExpiryDate', label: '最近期效' },
    { prop: 'createBy', label: '创建人员' },
    { prop: 'createTime', label: '创建时间' },
    { prop: 'updateBy', label: '更新人' },
    { prop: 'updateTime', label: '更新时间' },
    {
        prop: 'action',
        label: '操作',
        type: 'action',
        width: 120,
        componentProps: {
            fixed: 'right',

        },
        buttonGroup: [
            {
                label: '详情', type: 'text',permissions:'btn-inventory-xq', click: (row: any) => {
                    updataRef.value?.open1(row.drugId, formData.value.storageId)
                }
            },
            // {
            //     label: '复制', type: 'text', click: (row: any) => {
            //         //console.log('复制', row)
            //     }
            // },
            // {
            //     label: '启用', statusName: ['isEnabled'], status: '停用', type: 'text', click: (row: any) => {
            //         enableProfile(row.drugId ?? 0).then((res) => {
            //             if (res.code == '200') {
            //                 getDrugProfileListApi(); // 刷新列表
            //                 ElMessage({
            //                     type: 'success',
            //                     message: '操作成功',
            //                 });
            //             } else {
            //                 ElMessage({
            //                     type: 'warning',
            //                     message: res.msg,
            //                 });
            //             }


            //         });
            //     }
            // },
            // {
            //     label: '停用', statusName: ['isEnabled'], status: '启用', type: 'text', color: '#D90000', click: (row: any) => {
            //         deleteProfile(row.drugId ?? 0).then((res) => {
            //             if (res.code == '200') {
            //                 getDrugProfileListApi(); // 刷新列表
            //                 ElMessage({
            //                     type: 'success',
            //                     message: '操作成功',
            //                 });
            //             } else {
            //                 ElMessage({
            //                     type: 'warning',
            //                     message: res.msg,
            //                 });
            //             }

            //         });


            //     }
            // },
            {
                label: '删除',permissions:'btn-inventory-del',type: 'text', color: '#D90000', click: (row: any) => {

                    ElMessageBox.alert('确定要删除吗？', '删除药品', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        callback: (action: any) => {

                            if(action == 'cancel'){
                                return;
                            }
                            deleteProfile(row.drugId ?? 0).then((res) => {
                                if (res.code == '200') {
                                    getDrugProfileListApi(); // 刷新列表
                                    ElMessage({
                                        type: 'success',
                                        message: '操作成功',
                                    });
                                } else {
                                    // ElMessage({
                                    //     type: 'warning',
                                    //     message: res.msg,
                                    // });
                                }

                            });

                        },
                    })
                }
            }
        ]
    }
]
const tableData = ref<DrugInfo[]>([])
const name = ref<string>('')
const radio1 = ref<number>(0)

const selectionChange = (val: any) => {
    //console.log('选中数据:', val);
};
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const getDrugProfileListApi = async () => {
    loading.value = true
    formData.value.pageNo = currentPage.value;
    formData.value.pageSize = pageSize.value;
    let res = await getDrugProfileList(formData.value)
    if(res.code != '200'){
        //ElMessage.error(res.msg);
        return;
    }
    for (let index = 0; index < res.data.list.length; index++) {
        let item = res.data.list[index];

        if (item) {
            //  
            let minPackUnitText = item.minPackUnitText
            let packUnitText = item.packUnitText
            // for (let index = 0; index < UnitTypeEnum.value.length; index++) {
            //     let items = UnitTypeEnum.value[index];
            //     if (items.unitCode == item.minPackUnit) {
            //         minPackUnit = items.unitText
            //     }
            //     if (items.unitCode == item.packUnit) {
            //         packUnit = items.unitText
            //     }
            // }
            // {text: "成药", value: "1"}

            // {text: "中药", value: "2"}

            // {text: "耗材", value: "3"}
            if(Number(item.price) > 0){
                item.price = (item.price / 100).toFixed(2)
            }
            if (item.drugCategory == '1') {
                item.guige = item.drugDosage + '' + item.drugDosageUnitText + '*' + item.minPackQty + minPackUnitText + '/' + packUnitText

            }
            if (item.drugCategory == '2') {
                item.guige = '-'

            }
            if (item.drugCategory == '3') {
                item.guige = (item.minPackQty || '') + (minPackUnitText || '') + '/' + packUnitText

            }

            item.isSplit = item.isSplit == '1' ? '是' : '否'
            item.stockQtyText = (item.stockQty ? item.stockQty + ( packUnitText || ''): 0 ) +  (item.minStockQty? item.minStockQty +( minPackUnitText || ''):'')
        }
        for (let index2 = 0; index2 < DrugCategoryEnum.value.length; index2++) {
            let item2 = DrugCategoryEnum.value[index2];
            if (item && item.drugCategory == item2.value) {
                item.drugCategory = item2.text
            }
        }

    }
    tableData.value = res.data.list
    total.value = res.data.totalCount
    loading.value = false

}
getDrugProfileListApi()

const handlePageChange = (page: number) => {
    //console.log('当前页:', page);
    currentPage.value = page;
    getDrugProfileListApi()

};
const handleSizeChange = (size: number) => {
    //console.log('每页条数:', size);
    currentPage.value = 1;
    pageSize.value = size;
    getDrugProfileListApi()

};
const RadioGroupBtnChange = (e: number) => {
    //console.log(e, 'RadioGroupBtnChange');
    currentPage.value = 1;
    radio1.value = e
    formData.value.drugCategory = e
    handlePageChange(1)
    getDrugProfileListApi()

}

</script>

<style lang="scss">
.InventoryManage {
    padding: 24px;
    height: 100%;
}

.InventoryManage-page {
    background: #fff;
    border-radius: 6px;
    height: 100%;

    .InventoryManage-page-content {
        padding: 21px 24px;
        height: calc(100% - 50px);

        .InventoryManage-page-form {
            display: flex;
            align-items: center;

            .InventoryManage-page-form-right {
                margin-left: auto;
            }
        }

       

        .InventoryManage-page-pagination {
            margin-top: 24px;
            display: flex;
            align-items: center;

            .InventoryManage-page-pagination-total {
                margin-right: auto;
                font-family: Microsoft YaHei, Microsoft YaHei;
                font-weight: 400;
                font-size: 14px;
                color: rgba(0, 0, 0, 0.6);
                text-align: left;
                font-style: normal;
                text-transform: none;
            }
        }
    }
    .InventoryManage-page-table {
        margin-top: 22px;
        height: calc(100vh - 300px);
    }
}
</style>